<template>
	<view class="login-container">
		<cu-custom bgColor="bg-gradual-blue" :isBack="true">
			<template v-slot:content>登录</template>
		</cu-custom>

		<view class="padding-xl">
			<view class="text-center margin-bottom-xl">
				<text class="text-xxl text-bold text-shadow">智慧餐厅</text>
			</view>

			<form>
				<view class="cu-form-group">
					<view class="title">手机号</view>
					<input placeholder="请输入手机号" v-model="phone" type="number" />
				</view>
				<view class="cu-form-group">
					<view class="title">密码</view>
					<input placeholder="请输入密码" v-model="password" type="password" />
				</view>
				<view class="cu-form-group">
					<view class="title">验证码</view>
					<input placeholder="请输入验证码" v-model="captcha" type="text" />
					<view class="cu-capsule radius" @click="refreshCaptcha">
						<image :src="captchaUrl" mode="aspectFit" style="width: 120rpx; height: 50rpx" v-if="captchaUrl" />
						<view class="cu-tag bg-white" v-else>加载中</view>
					</view>
				</view>

				<view class="padding-xl">
					<button class="cu-btn block bg-gradual-blue lg" @click="handleLogin" :loading="loginLoading">
						{{ loginLoading ? '登录中...' : '立即登录' }}
					</button>
				</view>
			</form>

			<view class="flex justify-between padding-lr-xl">
				<navigator url="/pages/forget/forget" class="text-blue">忘记密码</navigator>
				<navigator url="/pages/register/register" class="text-blue">注册账号</navigator>
			</view>
		</view>

		<view class="wechat-login-container">
			<view class="text-center padding-top-xl">
				<view class="text-gray">————— 其他登录方式 —————</view>
				<view class="margin-top-xl">
					<button class="cu-btn round bg-green shadow" @click="wechatLogin">
						<text class="cuIcon-weixin"></text>
						微信快捷登录
					</button>
				</view>
			</view>
		</view>
	</view>
</template>

<script setup>
import { ref, onMounted } from 'vue';
import { post, get } from '@/utils/request.js'; 

// 表单数据（保持不变）
const phone = ref('');
const password = ref('');
const loginLoading = ref(false);
const captcha = ref('');
const captchaUrl = ref(''); 
const captchaKey = ref('');

// 获取验证码（保持不变）
const getCaptcha = async () => {
  try {
    const response = await get('/captcha/code', {
      responseType: 'arraybuffer' ,
     headers: { 'Accept': 'application/json' }
    });
    console.log('验证码响应:', response); 
    const base64 = uni.arrayBufferToBase64(response.data);
   
    captchaUrl.value = `data:image/png;base64,${base64}`;
    const key = response.header['x-captcha-key'] || response.header['key']
  if (key) {
      captchaKey.value = key;
      console.log('获取到验证码Key:', captchaKey.value);
      // 保存到变量（如 captchaKey.value = captchaKey;）
    } else {
      console.error('响应头中未找到 X-Captcha-Key');
    }
  } catch (err) {
    console.error('获取验证码失败:', err);
    uni.showToast({ title: '验证码获取失败', icon: 'none' });
  }
};

// 刷新验证码（保持不变）
const refreshCaptcha = () => {
  getCaptcha();
};

// 登录逻辑（保持不变）
const handleLogin = async () => {
  if (!captchaKey.value) {
   return uni.showToast({title:'请先获取验证码',icon:'none'}) 
  }
  // 表单验证
  if (!phone.value.trim() || !captcha.value.trim() || !password.value.trim()) {
    return uni.showToast({ title: '请填写完整信息', icon: 'none' });
  }

  loginLoading.value = true;
  try {
    console.log('发送的验证码Key:', captchaKey.value);
    // 关键：正确的URL、参数、请求头
    const res = await post('/login/index', {
    
      account: phone.value,
      password: password.value,
      inputCaptcha: captcha.value,
      key: captchaKey.value
      
    }, {
      // 可选：若需传递额外配置（如超时时间）
      timeout: 10000
    });
    if (res.data.code !== 200) {
      uni.showToast({ title: res.data.msg, icon: 'none' });
      refreshCaptcha(); // 刷新验证码
      return;
    }
    console.log('登录响应:', res); // 查看后端返回数据
    uni.setStorageSync('token', res.data.msg.token); // 保存token到本地
    uni.setStorageSync('user', JSON.stringify(res.data.msg.user)); // 保存用户信息到本地
    uni.setStorageSync('loginTime', Date.now()); // 记录登录时间

    uni.showToast({ title: '登录成功', icon: 'success' });
    setTimeout(() => uni.switchTab({ url: '/pages/index/HomePage' }), 1000);
  } catch (err) {
    console.error('登录错误:', err);
    uni.showToast({ 
      title: err.message || '登录失败，请重试', 
      icon: 'none' 
    });
    refreshCaptcha(); 
  } finally {
    loginLoading.value = false;
  }
};
// 微信快捷登录（保持不变）
const wechatLogin = () => {
  uni.login({
    provider: 'weixin',
    success: (res) => {
      console.log('微信登录 Code:', res.code);
      uni.showToast({ title: '微信登录成功', icon: 'success' });
    },
    fail: (err) => {
      uni.showToast({ title: '微信登录失败', icon: 'none' });
      console.error(err);
    }
  });
};

// 页面加载时自动获取验证码（保持不变）
onMounted(() => {
   captchaKey.value = ''; // 清空旧 key
  captcha.value = '';    // 清空输入框
  getCaptcha();
});
</script>

<style scoped>
.login-container {
	background-color: #f8f8f8;
	min-height: 100vh;
}
.wechat-login-container {
	position: fixed;
	bottom: 50rpx;
	width: 100%;
}
</style>